﻿Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Public Class perSeguranca
    Inherits perPadrao

#Region "Criptografia"

    Private Shared TripleDES As New TripleDESCryptoServiceProvider
    Private Shared MD5 As New MD5CryptoServiceProvider
    ' Definição da chave de encriptação/desencriptação 
    Private Const key As String = "CHAVE12345teste"

    ''' <summary> 
    ''' Calcula o MD5 Hash  
    ''' </summary> 
    ''' <param name="value">Chave</param> 
    Public Shared Function MD5Hash(ByVal value As String) As Byte()
        ' Converte a chave para um array de bytes  
        Dim byteArray() As Byte = ASCIIEncoding.ASCII.GetBytes(value)
        Return MD5.ComputeHash(byteArray)
    End Function

    ''' <summary> 
    ''' Encripta uma string com base em uma chave 
    ''' </summary> 
    ''' <param name="sSenha">String a encriptar</param> 
    Public Function criptografar(ByVal sSenha As String) As String

        Try
            ' Definição da chave e da cifra (que neste caso é Electronic 
            ' Codebook, ou seja, encriptação individual para cada bloco) 
            TripleDES.Key = MD5Hash(key)
            TripleDES.Mode = CipherMode.ECB
            ' Converte a string para bytes e encripta 
            Dim Buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(sSenha)
            Return Convert.ToBase64String(TripleDES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
        Catch ex As Exception
            Throw New Exception("Ocorreu um erro no método 'criptografar'. " & Environment.NewLine & Environment.NewLine & ex.Message)
        End Try

    End Function

    ''' <summary> 
    ''' Desencripta uma string com base em uma chave 
    ''' </summary> 
    ''' <param name="sSenha">String a decriptar</param> 
    Public Function descriptografar(ByVal sSenha As String) As String

        Try
            ' Definição da chave e da cifra 
            TripleDES.Key = MD5Hash(key)
            TripleDES.Mode = CipherMode.ECB
            ' Converte a string encriptada para bytes e decripta 
            Dim Buffer As Byte() = Convert.FromBase64String(sSenha)
            Return ASCIIEncoding.ASCII.GetString(TripleDES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
        Catch ex As Exception
            Throw New Exception("Ocorreu um erro no método 'descriptografar'. " & Environment.NewLine & Environment.NewLine & ex.Message)
        End Try

    End Function

#End Region

#Region "Backup"
    Public Function GerarBackup(ByVal Diretorio As String) As Boolean
        Dim sSql As String
        Dim sBanco As String

        Try
            sBanco = MyBase.DataBase
            sSql = " BACKUP DATABASE [" & sBanco & "] TO DISK = '" & Diretorio & "'"

            MyBase.executarAcao(sSql)
            Return True
        Catch ex As Exception

            Throw New Exception("Exceção no método 'GerarBackup'." & Environment.NewLine & Environment.NewLine & ex.Message)
            Return False

        End Try
    End Function
    Public Function RestaurarBackup(ByVal Diretorio As String, ByVal sSenha As String) As Boolean
        Dim sSql As String
        Dim sBanco As String
        Dim bRetorno As Boolean = True
        Dim sConexao As String
        Dim Cmd As New System.Data.SqlClient.SqlCommand
        Dim Cnn As New System.Data.SqlClient.SqlConnection

        Try
            sBanco = MyBase.DataBase
            sConexao = "User ID=SA;Password=" & sSenha.Trim & ";Initial Catalog=" & sBanco & ";Data Source= " & MyBase.DataSource.ToString.Trim
            Cnn.ConnectionString = sConexao

            If (Cnn.State = ConnectionState.Closed) Then
                Cnn.Open()
                Cmd.Connection = Cnn
                Cmd.CommandType = CommandType.Text
            End If
            Dim caminhoMDF As String = Me.DiretorioMdf
            sSql = "USE MASTER "
            sSql &= "RESTORE DATABASE [" & caminhoMDF & "] FROM DISK = '" & Diretorio & "' WITH REPLACE, RECOVERY, FILE=1, STATS=10;"
            Cmd.CommandText = sSql
            Cmd.ExecuteNonQuery()
            bRetorno = True
        Catch ex As Exception
            bRetorno = False
            Throw New Exception("Exceção no método 'RestaurarBackup'." & Environment.NewLine & Environment.NewLine & ex.Message)

        End Try

        Return bRetorno

    End Function
    Public Function DiretorioMdf() As String

        Return MyBase.DiretorioBanco

    End Function
    Public Function Servidor() As String

        Return MyBase.DataSource

    End Function
    Public Function NomeBanco() As String

        Return MyBase.DataBase

    End Function
#End Region



End Class
